import React, {Component} from 'react';
import BraftEditor from 'braft-editor';
import {Upload} from 'antd';
import {PictureFilled} from '@ant-design/icons';

const ContentUtils = require('braft-utils').ContentUtils;
import 'braft-editor/dist/index.css';
import styles from './index.less'
import {request} from 'umi';
import APIS from '@/apis';
import Const from '@/common/Const';
import {RcCustomRequestOptions} from 'antd/lib/upload/interface';
import URLS from '@/apis/APIUrlDefine';

interface Props {
  OnContentChanged?: (v: string) => any,
  ContentInitialValue?: string;
  ref?: any;
}

class RichTextEditor extends Component<Props> {
  state = {
    editorState: BraftEditor.createEditorState(this.props.ContentInitialValue ? this.props.ContentInitialValue : ''), // 设置编辑器初始内容
    outputHTML: '<p></p>',
  };
  isLivinig = false;

  componentDidMount() {
    this.isLivinig = true;
    // 3秒后更改编辑器内容
  }

  reload = () => {
    this.setState({editorState: BraftEditor.createEditorState(this.props.ContentInitialValue ? this.props.ContentInitialValue : '')});
  }

  componentWillUnmount() {
    this.isLivinig = false;
  }

  handleChange = (editorState: any) => {
    this.setState({
      editorState: editorState,
      outputHTML: editorState.toHTML(),
    });
    this.props.OnContentChanged?.(editorState.toHTML())
  };

  setEditorContentAsync = () => {
    this.isLivinig &&
    this.setState({
      editorState: BraftEditor.createEditorState(this.props.ContentInitialValue ? this.props.ContentInitialValue : '<p>HelloWorld!</p>'),
    });
  };
  uploadHandler = async (param: RcCustomRequestOptions) => {
    if (!param.file) {
      return false;
    }
    var data = new FormData()
    data.append('filename', param.file)
    data.append('type', '1')
    var result = await request('/api/utils/v1/upload', {
      method: 'POST',
      data: data,
    }).catch((ex) => {
    })
    if (result) {
      var asset = await APIS.AssetAPI.CreateNewAsset({
        url: result.data,
        type: Const.ASSET_TYPE.IMAGE_TYPE,
      }).catch(() => {
      });
    }
    this.setState({
      editorState: ContentUtils.insertMedias(this.state.editorState, [
        {
          type: 'IMAGE',
          url: URLS.SERVER_PICTURE_URL + asset.data?.url,
        },
      ]),
    });
    return true;
  }


  render() {
    const controls: any = [
      'blockquote',
      'bold',
      'code',
      'clear',
      'emoji',
      'font-family',
      'font-size',
      'fullscreen',
      'headings',
      'hr',
      'italic',
      'letter-spacing',
      'line-height',
      'link',
      'list-ol',
      'list-ul',
      'media',
      'redo',
      'remove-styles',
      'separator',
      'strike-through',
      'superscript',
      'subscript',
      'text-align',
      'text-color',
      'text-indent',
      'underline',
      'undo',
      'table',
    ];
    const extendControls: any = [
      {
        key: 'antd-uploader',
        type: 'component',
        component: (
          <Upload accept="image/*" showUploadList={false} customRequest={this.uploadHandler.bind(this)}>
            <button
              type="button"
              className="control-item button upload-button"
              data-title="插入图片"
            >
              <PictureFilled/>
            </button>
          </Upload>
        ),
      },
    ];
    return (
      <div>
        <div className={styles["editor-wrapper"]}>
          <BraftEditor
            style={{}}
            controls={controls}
            placeholder={'请输入!'}
            value={this.state.editorState}
            extendControls={extendControls}
            onChange={this.handleChange}
          />
        </div>
      </div>
    );
  }
}

export default RichTextEditor;
